/* Copyright (c) 2010 Kevin <cn0819@gmail.com>
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2010-09-14 16:30:56 $
 *
 * Version 0.1
 */
 var xxx = null;
(function($) {
    $.fn.dataTable = function(_opt){
        return $(this).each(function(){
			var opt = {
				url : '',
				colNames : [],
				columns : [],
				multiselect : false,
				rownum : 10,
				rowsList : [10, 20, 30, 50, 100],
				page : 1,
				pager : false,
				caption : 'datatable',
				nodata : '没有数据',
				tblStatus : ''
			};
			var colOpt = {
				name : '',
				width : null,
				align : 'left',
				key : false,
				sort : false,
				tpl : null
			};
			opt = $.extend(opt, _opt);
			opt.colsLen = opt.colNames.length;
			if(opt.colNames.length != opt.columns.length){
				alert('colNames 长度与 columns 长度不一致！');
				return;
			}
			var dt = $(this);
			dt.empty().addClass('zz-datatable');
			//生成html
			var html = '';
			html += '<table cellspacing="1" cellpadding="4">';
			html += '<thead>';
			html += '<tr>';
			for(var c=0; c<opt.colsLen; c++){
				html += '<th';
				if(opt.columns[c].width != null) html += ' width="'+opt.columns[c].width+'"';
				html += '>';
				if(opt.columns[c].sort){
					html += '<a href="###" key="'+opt.columns[c].name+'" order="">'+opt.colNames[c]+'</a>';
				}else{
					html += opt.colNames[c];
				}
				html += '</th>';
				opt.columns[c] = $.extend({}, colOpt, opt.columns[c]);
			}
			html += '</tr>';
			html += '</thead>';
			html += '<tbody>';
			html += '</tbody>';
			html += '</table>';
			dt.html(html);
			dt.find('thead a').click(function(){
				var key = $(this).attr('key');
				var order = $(this).attr('order') == 'asc' ? 'desc' : 'asc';
				$(this).attr('order', order)
				if(key == opt._sort){
					order = 'desc';
				}
				dt.find('thead img').remove();
				$(this).append(' <img src="images/datatable/'+order+'.png" border="0" />');
				getData({sort : key + ' ' + order});
			});
			
			var exportTable = function(more){
				var form = $('<form action="'+opt.url+'" method="POST"><input type="hidden" name="tblExport" value="1" /><input type="hidden" name="tblStatus" value="'+opt.tblStatus+'" /></form>');
				$('body').append(form);
				form.submit();
			};
			
			var getData = function(more){
				var post_data = {page : opt.page, rows : opt.rownum, tblStatus : opt.tblStatus};
				if(typeof(more) == 'object') $.extend(post_data, more);
				$.ajax({
					url : opt.url,
					type : 'POST',
					data : post_data,
					dataType : 'json',
					success : function(_data, _status){
					var page = _data.page;
					var records = _data.records;
					var data = _data.data;
					var html = '';
					for(var r=0; r<data.length; r++){
						html += '<tr>';
						for(var c=0; c<opt.colsLen; c++){
							var index = opt.columns[c].name;
							html += '<td';
							if(opt.columns[c].align != null) html += ' align="'+opt.columns[c].align+'"';
							html += '>';
							if(opt.columns[c].tpl != null){
								var _tpl = opt.columns[c].tpl;
								var _var = _tpl.match(/\{\$(\w+)\}/g);
								for(var vi=0; vi < _var.length; vi++){
									var key = _var[vi].substring(2, _var[vi].length-1);
									_tpl = _tpl.replace(_var[vi], data[r][key]== null ? '' : data[r][key]);
								}
								html += _tpl;
							}else{
								html += data[r][index] == null ? '' : data[r][index];
							}
							html += '</td>';
						}
						html += '</tr>';
					}
					if(data.length == 0) html = '<tr><td colspan="'+opt.colsLen+'" align="center">'+opt.nodata+'</td></tr>';
					dt.find('tbody').html(html);
					dt.find('tbody tr').unbind().bind('mouseover', function(){ $(this).addClass('hover'); } ).bind('mouseout', function(){ $(this).removeClass('hover'); } );
					//分页
					if(opt.pager){
						var pagecount = Math.ceil(records/opt.rownum);
						var select = '<select>';
						for(var i=0; i<opt.rowsList.length; i++){
							 select += '<option value="'+opt.rowsList[i]+'"'+(opt.rowsList[i] == opt.rownum ? ' selected="selected"' : '')+'>'+opt.rowsList[i]+'</option>';
						}
						select += '</select>';
						$(opt.pager).addClass('zz-pager').html('<table align="center"><tr><td>总共有 <strong>'+records+'</strong> 条数据，每页显示 '+select+' 条，共 <strong>'+pagecount+'</strong> 页 </td><td></td></tr></table>');
						$(opt.pager).find('select').change(function(){
							opt.rownum = $(this).val();
							getData();
						});
						$(opt.pager).find('td:last').pager({ pagenumber: page, pagecount: pagecount, buttonClickCallback : function(page){
							opt.page = page;
							getData();
						}});
					}
					
				}}
				);
			}
			
			this.exportTable = exportTable;
			this.getData = getData;
			
			//初始载入数据
			getData();
		});
	};
	
	//重新载入表格
	$.fn.reloadTable = function(more) {
        return $(this).each(function() {
			this.getData(more);
        });
    };
	
	//导出表格
	$.fn.exportTable = function(more) {
        return $(this).each(function() {
			this.exportTable(more);
        });
    };
	
	//分页插件
	$.fn.pager = function(options) {
        var opts = $.extend({}, $.fn.pager.defaults, options);
        return this.each(function() {
            $(this).empty().append(renderpager(parseInt(options.pagenumber), parseInt(options.pagecount), options.buttonClickCallback)); 
            $('.pages a').mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });
        });
    };

    function renderpager(pagenumber, pagecount, buttonClickCallback) {

        var $pager = $('<div class="pages"></ul>');
        $pager.append(renderButton('first', pagenumber, pagecount, buttonClickCallback)).append(renderButton('prev', pagenumber, pagecount, buttonClickCallback));

        var startPoint = 1;
        var endPoint = 9;
        if (pagenumber > 4) {
            startPoint = pagenumber - 4;
            endPoint = pagenumber + 4;
        }
        if (endPoint > pagecount) {
            startPoint = pagecount - 8;
            endPoint = pagecount;
        }
        if (startPoint < 1) {
            startPoint = 1;
        }
        for (var page = startPoint; page <= endPoint; page++) {
            var currentButton = $('<a href="###">' + (page) + '</a>');
            page == pagenumber ? currentButton.addClass('current') : currentButton.click(function() { if(buttonClickCallback) buttonClickCallback(this.firstChild.data); });
            currentButton.appendTo($pager);
        }
        $pager.append(renderButton('next', pagenumber, pagecount, buttonClickCallback)).append(renderButton('last', pagenumber, pagecount, buttonClickCallback));

        return $pager;
    }

    function renderButton(buttonLabel, pagenumber, pagecount, buttonClickCallback) {
		var labelText = {
			'first' : '首页',
			'prev' : '上页',
			'next' : '下页',
			'last' : '末页'
		};
        var $Button = $('<a href="###">' + labelText[buttonLabel] + '</a>');
		
        var destPage = 1;
        switch (buttonLabel) {
            case "first":
                destPage = 1;
                break;
            case "prev":
                destPage = pagenumber - 1;
                break;
            case "next":
                destPage = pagenumber + 1;
                break;
            case "last":
                destPage = pagecount;
                break;
        }
        if (buttonLabel == "first" || buttonLabel == "prev") {
            pagenumber <= 1 ? $Button.addClass('disabled') : $Button.click(function() { if(buttonClickCallback) buttonClickCallback(destPage); });
        }
        else {
            pagenumber >= pagecount ? $Button.addClass('disabled') : $Button.click(function() { if(buttonClickCallback) buttonClickCallback(destPage); });
        }
        return $Button;
    }

    $.fn.pager.defaults = {
        pagenumber: 1,
        pagecount: 1
    };
})(jQuery);